package com.mingtu.jgspatrol.fragment;

import static com.mingtu.jgspatrol.utils.MyConstant.animationType;
import static com.mingtu.jgspatrol.utils.MyConstant.isFirstOnly;
import static com.mingtu.jgspatrol.utils.MyConstant.isOpenLoadAnimation;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.base.BaseBindingFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.room.ReportedEvent;
import com.mingtu.common.room.ReportedEventDao;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.activity.ReportedDetailsActivity;
import com.mingtu.jgspatrol.adapter.MyRecordReportAdapter;
import com.mingtu.jgspatrol.bean.MyReportRecordBean;
import com.mingtu.jgspatrol.databinding.FragmentReportRecordBinding;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MyReportRecordFragment extends BaseBindingFragment<FragmentReportRecordBinding> implements LazyFragmentPagerAdapter.Laziable {
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private MyRecordReportAdapter myRecordReportAdapter;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String beginTime = null;
    private String endTime = null;

    public static MyReportRecordFragment getInstance() {
        MyReportRecordFragment ef = new MyReportRecordFragment();
        return ef;
    }

    public static MyReportRecordFragment getInstance(String beginTime, String endTime) {
        MyReportRecordFragment ef = new MyReportRecordFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_PARAM1, beginTime);
        bundle.putString(ARG_PARAM2, endTime);
        ef.setArguments(bundle);
        return ef;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            beginTime = getArguments().getString(ARG_PARAM1);
            endTime = getArguments().getString(ARG_PARAM2);
        }
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_report_record;
    }

    @Override
    protected void initData() {

        initListener();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initView() {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        binding.recycler.setLayoutManager(manager1);
        binding.recycler.addItemDecoration(new TopSpaceItemDecoration());
        binding.recycler.addItemDecoration(new BottomSpaceItemDecoration());


        myRecordReportAdapter = new MyRecordReportAdapter(context);
        if (isOpenLoadAnimation) {
            myRecordReportAdapter.isFirstOnly(isFirstOnly);
            myRecordReportAdapter.openLoadAnimation(animationType);
        }

        myRecordReportAdapter.setEmptyView(new EmptyDataLayout(context));
        binding.recycler.setAdapter(myRecordReportAdapter);
        myRecordReportAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MyReportRecordBean.PageBean.ListBean listBean = myRecordReportAdapter.getData().get(position);
                String eventId = listBean.getId();
                boolean isUpload = listBean.isUpload();
                if (isUpload) {
                    Bundle bundle = new Bundle();
                    bundle.putString("eventId", eventId);
                    IntentUtils.getInstance().readyGo(getActivity(), ReportedDetailsActivity.class, bundle);
                } else {
                    ToastUtils.showLong("已经上报的记录才能查看详情哦~");
                }
            }
        });
    }

    @Override
    protected void getData() {
        getRepordRecord(1);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe
    public void onStringEvent(MyEventBus event) {
        //当用户处在次页面的时候，联网之后刷新数据
        String message = event.getMessgae();
        if (message.equals(Constant.REFRESH_MY_REPORT_DATA)) {
            try {
                getRepordRecord(1);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                binding.srlUp.setNoMoreData(false);
                currentPage = 1;
                getRepordRecord(1);
            }
        });
    }

    private void initLoadMoreListener() {
        binding.srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(myRecordReportAdapter.getData(), Constant.PAGE_SIZE);
                    getRepordRecord(currentPage);
                }
                binding.srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 上报记录
     */
    private void getRepordRecord(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("beginTime", beginTime);
        hashMap.put("endTime", endTime);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_REPORT_EVENT_LIST_STAFF)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                MyReportRecordBean myReportRecordBean = new MyReportRecordBean();
                                myReportRecordBean = gson.fromJson(result, MyReportRecordBean.class);

                                List<MyReportRecordBean.PageBean.ListBean> dataBeans = myReportRecordBean.getPage().getList();


                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;

                                        //设置为已经上报
                                        for (int i = 0; i < dataBeans.size(); i++) {
                                            MyReportRecordBean.PageBean.ListBean listBean = dataBeans.get(i);
                                            listBean.setUpload(true);
                                        }

                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            myRecordReportAdapter.replaceData(dataBeans);
                                        } else {
                                            myRecordReportAdapter.addData(dataBeans);
                                        }
                                        noUploadData();
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                        noUploadData();
                    }
                });
    }


    /**
     * 未上传的数据
     */
    private void noUploadData() {
        //未上传的数据
        List<MyReportRecordBean.PageBean.ListBean> dataBeans = new ArrayList<>();
        ReportedEventDao reportedEventDao = BaseApplication.getBaseApplication().getReportedEventDao();
        List<ReportedEvent> reportedEventList = reportedEventDao.getAll();
        for (int i = 0; i < reportedEventList.size(); i++) {
            ReportedEvent reportedEvent = reportedEventList.get(i);
            String createTime = reportedEvent.getCreateTime();
            String MyCreateTime = MyUtills.stampToDateTime2(String.valueOf(createTime));
            String address = reportedEvent.getAddress();
            String uploadType = reportedEvent.getUploadType();
            MyReportRecordBean.PageBean.ListBean listBean = new MyReportRecordBean.PageBean.ListBean();

            listBean.setUpload(false);
            listBean.setCreateTime(MyCreateTime);
            listBean.setAddress(address);
            listBean.setType(uploadType);
            dataBeans.add(listBean);
        }
        if (dataBeans.size() > 0) {
            myRecordReportAdapter.addData(0, dataBeans);
        }
    }

}